package com.example.sql_valid.controller;

import com.example.sql_valid.controller.Response.ValidationResponse;
import com.example.sql_valid.service.SQLValidatorService;
import com.example.sql_valid.service.SQLValidatorServiceV1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/sql-validator")
public class SQLValidatorController {


    private static final String ERROR_FILE_DIRECTORY = "errors";
    @Autowired
    private SQLValidatorService sqlValidatorService;

    @Autowired
    private SQLValidatorServiceV1 sqlValidatorServiceV1;

    @PostMapping("/validateSchema")
    public ResponseEntity<ValidationResponse> validateSQL(@RequestParam("files") List<MultipartFile> files,
                                                          @RequestParam("schema") String schema,
                                                          @RequestParam("checkTablespace") boolean checkTablespace,
                                                          @RequestParam("isOB") boolean isOB) {

        ValidationResponse result = sqlValidatorServiceV1.SchemaValid(files, schema, checkTablespace,isOB);
        return ResponseEntity.ok(result);
    }


    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> downloadErrorFile(@PathVariable String fileName) throws IOException {
        System.out.println(fileName);
        Path filePath = Paths.get(ERROR_FILE_DIRECTORY, fileName);
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(filePath));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(Files.size(filePath))
                .body(resource);
    }

}


